<template>
  <div class="app-container">
    <div
      v-show="
        !licenseInfo.visible &&
        !productInfo.visible &&
        !createPurchInfo.visible &&
        !createUseInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :listTypeInfo="listTypeInfo"
          :filter-btn="filterInfo.searchBtn"
        />
      </div>
      <modelTips
        :items="modelTipsInfo.items"
        :title="modelTipsInfo.title"
        :brackets="true"
      />
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="btnList">
          <template v-slot:filter-purchApplication>
            <el-button :disabled="!canDo" @click="createPurchApplicationOrder"
              >生成申购单</el-button
            >
          </template>
          <template v-slot:filter-useApplication>
            <el-button :disabled="!canDo" @click="createUseApplicationOrder"
              >生成领用申请</el-button
            >
          </template>
        </new-page-filter>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-licenseNumber="scope">
          <p
            v-if="$permission('stockWarningLicense:details')"
            class="slip-edit"
            @click="showLicenseDetail(scope.row.licenseId, scope.row)"
          >
            {{ scope.row.licenseNumber || '-' }}
          </p>
          <p v-else>{{ scope.row.licenseNumber || '-' }}</p>
          <p>{{ scope.row.brandName || '-' }}</p>
        </template>
        <template v-slot:col-commonName="scope">
          <p
            v-if="$permission('stockWarningProduct:details')"
            class="slip-edit"
            @click="showProductDetail(scope.row.productId, scope.row)"
          >
            {{ scope.row.commonName || '-' }}
          </p>
          <p v-else>{{ scope.row.commonName || '-' }}</p>
          <p>{{ scope.row.productCode || '-' }}</p>
          <p>{{ scope.row.alias || '-' }}</p>
        </template>
        <template v-slot:col-type="scope">
          <p>{{ scope.row.productTypeValue || '-' }}</p>
          <p>{{ scope.row.codeTypeValue || '-' }}</p>
          <p>{{ scope.row.productCategoryValue || '-' }}</p>
        </template>
        <template v-slot:col-supplierName="scope">
          <p>{{ scope.row.supplierName || '-' }}</p>
        </template>
        <template v-slot:col-standard="scope">
          <p>{{ scope.row.standard || '-' }}</p>
          <p>{{ scope.row.unitName || '-' }}</p>
        </template>
        <template v-slot:col-sumPrice="scope">
          <span>{{ (scope.row.price * scope.row.qty).toFixed(2) }}</span>
        </template>
      </table-container>
    </div>
    <license-details
      v-if="licenseInfo.visible"
      v-model:visible="licenseInfo.visible"
      :id="licenseInfo.id"
      @returnBack="getList"
    ></license-details>
    <product-details
      v-if="productInfo.visible"
      v-model:visible="productInfo.visible"
      :id="productInfo.id"
      @returnBack="getList"
    />
    <purch-application-modify
      v-if="createPurchInfo.visible"
      v-model:visible="createPurchInfo.visible"
      :title="createPurchInfo.title"
      :stock-waring-data="tableInfo.selections"
      :order-id="createPurchInfo.orderId"
      :product-ids="createPurchInfo.productIds"
      @returnModify="returnModify"
    />
    <use-application-modify
      v-if="createUseInfo.visible"
      v-model:visible="createUseInfo.visible"
      :title="createUseInfo.title"
      :stock-waring-data="tableInfo.selections"
      :order-id="createUseInfo.orderId"
      :depot-info="createUseInfo.depotInfo"
      :detail-data="createUseInfo.detailData"
      @returnModify="returnModify"
    />
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
      @reset="handleClose"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :disabled="formInfo.disabled"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-exportDepotName>
          <el-input
            v-model="formInfo.data.exportDepotName"
            class="not-mongolia"
            type="input"
            :disabled="true"
            placeholder="请选择领出仓库"
          >
            <template #append>
              <el-icon @click="selectDepotExport"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
    </page-dialog>
    <!-- 选择仓库 -->
    <SelectDepot
      v-if="depotInfo.visible"
      v-model:show-dialog="depotInfo.visible"
      :query="depotInfo.query"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectDepotCallback"
    />
  </div>
</template>

<script setup name="stockWarning">
import {
  warningStockPage,
  useApplicationDetailByProductIds,
} from '@/api/warning'
import { getDepotAll, getSupplierAll } from '@/api/core'
import LicenseDetails from './../../product/license/details'
import ProductDetails from './../../product/product/details'
import PurchApplicationModify from './purchApplication'
import UseApplicationModify from './useApplication'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const route = useRoute()

const createPurchInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const createUseInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
//颜色标识
const modelTipsInfo = ref({
  title: '类型',
  items: [
    {
      label: '高水位',
      style: { width: '10px', height: '10px', background: '#fceacb' },
    },
    {
      label: '低水位',
      style: { width: '10px', height: '10px', background: '#f5e4e4' },
    },
  ],
})
const listTypeInfo = ref({
  typeList: [],
  depotList: [],
  supplierList: [],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    depotId: '',
    depotAuth: 'id',
    typeMult: 'high,low',
    sort: 'qty asc',
  },
  list: [
    {
      label: '类型',
      value: 'typeMult',
      asValue: 'typeMult',
      componentType: 'select-model',
      code: 'warning_stock',
      event: search,
      multiple: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      event: search,
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '1',
      },
      api: getDepotAll,
    },
    {
      componentType: 'select',
      label: '供应商名称',
      value: 'supplierIdMult',
      list: 'supplierList',
      event: search,
      hidden: false,
      show: true,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
})
const btnList = ref([
  {
    type: 'slot',
    value: 'purchApplication',
    show: proxy.$permission('purchApplication:add'),
  },
  {
    type: 'slot',
    value: 'useApplication',
    show: proxy.$permission('useApplication:add'),
  },
])
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: warningStockPage,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: '150px',
    },
    {
      label: '供应商名称',
      value: 'supplierName',
      minWidth: 150,
      type: 'slot',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '仓库', value: 'depotName' },
    {
      label: '库存数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    { label: '高水位', value: 'highLevel', type: 'column' },
    { label: '低水位', value: 'lowLevel', type: 'column' },
  ],
})
const licenseInfo = ref({
  id: '',
  visible: false,
})
const productInfo = ref({
  id: '',
  visible: false,
})
// 弹窗相关
const dialogInfo = ref({
  visible: false,
  title: '选择领用出库仓库',
  btLoading: false,
  width: '600px',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '确定',
      type: 'primary',
      event: determine,
      show: true,
    },
  ],
})
const depotInfo = ref({
  visible: false,
  depotType: '',
  query: {
    idNotIn: '',
    useTypeId: '1',
    status: '1',
  },
})
//弹窗相关-表单相关
const formInfo = ref({
  ref: null,
  data: {
    exportDepotName: '',
    exportDepotId: '',
  },
  fieldList: [
    {
      label: '领出仓库',
      value: 'exportDepotName',
      type: 'slot',
    },
    {
      label: '领出部门',
      value: 'exportDeptName',
      type: 'input',
      disabled: true,
    },
  ],
  rules: {
    exportDepotName: [
      {
        required: true,
        message: '请选择出库仓库',
        trigger: 'blur',
      },
    ],
    exportDeptName: [
      { required: true, message: '请输入领出部门', trigger: 'blur' },
    ],
  },
  labelWidth: '100px',
})

const canDo = computed(() => {
  //判断所有数据的仓库ID是否一致
  if (
    tableInfo.value.selections.length > 0 &&
    tableInfo.value.selections.every(
      (item) => item.depotId === tableInfo.value.selections[0].depotId
    )
  ) {
    return true
  } else {
    return false
  }
})

watch(
  () => route.params,
  (val) => {
    const params = route.params
    const _paramsData = params.paramsData && JSON.parse(params.paramsData)
    if (
      params &&
      params.dataIndex !== undefined &&
      params.dataIndex !== null &&
      route.name === 'stockWarning'
    ) {
      filterInfo.value.query.typeMult = _paramsData.statusCode
      getList()
    }
  },
  {
    immediate: true,
    deep: true
  }
)

getList()
onMounted(() => {
  initDepotList()
  initSupplierList()
})

//生成申购单
function createPurchApplicationOrder() {
  let productIds = tableInfo.value.selections.map((row) => {
    return {
      productId: row.productId,
      lowLevel: row.lowLevel,
      qty: row.qty,
    }
  })
  createPurchInfo.value.visible = true
  createPurchInfo.value.title = '生成申购单'
  createPurchInfo.value.orderId = ''
  createPurchInfo.value.productIds = productIds
}
//生成领用申请
function createUseApplicationOrder() {
  dialogInfo.value.visible = true
}
function determine() {
  let productIds = tableInfo.value.selections.map((row) => row.productId)
  let storageDepotId = tableInfo.value.selections[0].depotId
  if (formInfo.value.data.exportDepotId) {
    let params = {
      productIds: productIds,
      exportDepotId: formInfo.value.data.exportDepotId,
      storageDepotId: storageDepotId,
    }
    useApplicationDetailByProductIds(params).then((resp) => {
      if (resp && resp.success) {
        resp.data.forEach((val) => {
          tableInfo.value.selections.forEach((item) => {
            if (item.productId === val.productId) {
              val.qty = proxy.$fn.Subtr(item.lowLevel || 0, item.qty || 0)
              val.calcQty = proxy.$fn.accMul(
                val.qty,
                val.unitConvertCoefficient || 0
              )
              val.largeUnitQty = proxy.$fn.accDiv(
                proxy.$fn.Subtr(val.calcQty, val.smallUnitQty || 0),
                val.unitConvertCoefficient || 0
              )
            }
          })
        })
        createUseInfo.value.visible = true
        createUseInfo.value.title = '生成领用申请单'
        createUseInfo.value.orderId = ''
        createUseInfo.value.detailData = resp.data.filter(
          (item) => item.qty > 0
        )
        handleClose()
      }
    })
  } else {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: '请选择领用出库仓库',
    })
  }
}
// 关闭弹窗前的回调
function handleClose() {
  dialogInfo.value.visible = false
  formInfo.value.data = {
    exportDepotId: '',
    exportDepotName: '',
    exportDeptName: '',
    exportDeptId: '',
  }
  emits('reset')
}
//选择领出仓库
function selectDepotExport() {
  let subDepotId = tableInfo.value.selections[0].depotId
  depotInfo.value.query.depotAuth = ''
  depotInfo.value.query.subDepotId = subDepotId
  depotInfo.value.visible = true
}
function selectDepotCallback(row) {
  let storageDepotName = tableInfo.value.selections[0].depotName
  let storageDepotId = tableInfo.value.selections[0].depotId
  let storageDeptName = tableInfo.value.selections[0].deptName
  let storagedeptId = tableInfo.value.selections[0].deptId
  if (row) {
    if (formInfo.value.data.exportDepotId !== row.id) {
      formInfo.value.data.exportDepotId = row.id
      formInfo.value.data.exportDepotName = row.name
      formInfo.value.data.exportDeptName = row.deptName ? row.deptName : ''
      formInfo.value.data.exportDeptId = row.deptId ? row.deptId : ''
    }
  } else {
    formInfo.value.data.exportDepotId = ''
    formInfo.value.data.exportDepotName = ''
    formInfo.value.data.exportDeptName = ''
    formInfo.value.data.exportDeptId = ''
  }
  createUseInfo.value.depotInfo = {
    deptName: storageDeptName,
    deptId: storagedeptId,
    depotName: storageDepotName,
    depotId: storageDepotId,
    exportDepotName: row.name,
    exportDepotId: row.id,
    exportDeptName: row.deptName,
    exportDeptId: row.deptId,
  }
}
function returnModify() {
  getList()
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function initDepotList() {
  const params = {
    depotAuth: 'id',
    useTypeId: '1',
    status: '1',
  }
  getDepotAll(params).then((resp) => {
    if (resp && resp.success) {
      if (resp.data.length) {
        listTypeInfo.value.depotList = resp.data.map((item) => {
          return {
            key: item.name,
            value: item.id,
          }
        })
      }
    }
  })
}
function initSupplierList() {
  let params = {}
  getSupplierAll(params).then((resp) => {
    if (resp && resp.success) {
      listTypeInfo.value.supplierList = resp.data.map((item) => {
        return {
          key: item.supplierName,
          value: item.supplierId,
        }
      })
    }
  })
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function showLicenseDetail(id, row) {
  sessionStorage.setItem('storeRowId', JSON.stringify(row))
  licenseInfo.value.visible = true
  licenseInfo.value.id = id
}
function showProductDetail(id, row) {
  sessionStorage.setItem('storeRowId', JSON.stringify(row))
  productInfo.value.visible = true
  productInfo.value.id = id
}
function tableRowClassName({ row = undefined }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && JSON.stringify(row) === rowId) {
    return 'check-row'
  } else if (row.qty > row.highLevel) {
    return 'nearly-row'
  } else if (row.qty <= row.lowLevel) {
    return 'expire-row'
  }
  return ''
}
</script>

<style scoped lang="scss">
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
